var config;//表格的配置文件
var missionId;//任务id编号
var userId;//当前用户id
var userName;//用户姓名

$(document).ready(function() {
    setUserId();
    showjsGrid();
});

//设置用户id
function setUserId() {
    var cookieStr = document.cookie.toString();
    var index = cookieStr.indexOf('userId');
    userId = cookieStr.substr(index).split('=')[1].split(';')[0];

    var index2 = cookieStr.indexOf('userName');
    userName = cookieStr.substr(index2).split('=')[1].split(';')[0];
}

function showjsGrid() {//当前工作事项页面展开效果
    //jsgrid组件的js，当点击当前页面的时候再加载表格的数据
     config = {
         width: "100%",
         height: (h - 200) + 'px',
         filtering: false,
         inserting: false,
         editing: false,
         sorting: true,
         paging: true,
         pageLoading: true,
         pageSize: 8,
         autoload: true,
         deleteConfirm: "确认需要删除数据？",
         loadMessage: "正在装载数据，请稍候......",

         rowClick: function (rowData) {       //点击某行数据触发该方法
             openDialog('.showDialog', function () {
                 var data = rowData.item;
                 $('.showDialog .proCategory').val(data.proCategory);
                 $('.showDialog .firstLevel').val(data.first_level);
                 $('.showDialog .secondLevel').val(data.second_level);
                 $('.showDialog .proDescribe').val(data.proDescription);
                 $('.showDialog .propertyRule').val(data.applicableLaws);
                 $('.showDialog .company').val(data.inspectedUnit);
                 $('.showDialog .department').val(data.cenManagement);
                 $('.showDialog .respUser').val(data.resPersonName);
                 $('.showDialog .filenameinput').val(data.supMaterial);
             });
         },
         controller: {
             loadData: function() {
                 var d = $.Deferred();
                 var url = (window.location.href).toString();//分解当前的url，获取problemId
                 var index = url.indexOf('?');
                 proId = url.substr(index + 1).split('=')[1];
                 $.ajax({
                     type: "post",
                     url: mmssm_url + 'inspectionscene/selectByProblemId',
                     dataType: "json",
                     data: {
                         problemId: proId
                     },
                 }).done(function(response) {
                     pagingdata = { data: response, itemsCount: response.length };
                     d.resolve(pagingdata);
                 }).fail(function () {
                     console.log("Table can't get data.")
                 });
                 return d.promise();
             },
             deleteItem: function (rowData) {
                 var supMaterial = rowData.supMaterial;
                 var id = rowData.id;
                 $.ajax({
                     url: mmssm_url + 'inspectionscene/delete',
                     type: 'POST',
                     dataType: 'json',
                     data: {
                         supMaterial: supMaterial,
                         id: id
                     },
                     success: function (data) {
                         if (data.toString() === 'success') {
                             alert("删除成功");
                             $('.jsgrid').jsGrid("render");//删除后刷新表格
                         } else {
                             alert('删除失败');
                         }
                         },
                     error: function (error) {
                              alert('删除失败');
                     }
                 });
             }
         },

         fields: [
             { name: 'id', title: '工单号', type: 'number', width: 5 },
             { name: "missionName", title: "巡察任务", type: "text", width: 40, validate: "required" },
             { name: "proCategory", title: "问题类别", type: "text", width: 50, validate: "required",
                 itemTemplate: function(value) {
                     return $("<div>").addClass("jsGridResizableDiv").text(value);
                 }
             },
             { name: "first_level", title: "一级问题", type: "text", width: 50,
                 itemTemplate: function(value) {
                     return $("<div>").addClass("jsGridResizableDiv").text(value);
                 }
             },
             { name: "second_level", title: "二级问题", type: "text", width: 50,
                 itemTemplate: function(value) {
                     return $("<div>").addClass("jsGridResizableDiv").text(value);
                 }
             },
             { name: "proDescription", title: "问题描述", type: "text", width: 50,
                 itemTemplate: function(value) {
                     return $("<div>").addClass("jsGridResizableDiv").text(value);
                 }
             },
             { name: "applicableLaws", title: "适用法规", type: "text", width: 40,
                 itemTemplate: function(value) {
                     return $("<div>").addClass("jsGridResizableDiv").text(value);
                 }
             },
             { name: "cenManagement", title: "归口（责任可查）", type: "text", width: 20 },
             { name: "resPersonName", title: "检查负责人", type: "text", width: 30 },
             { name: "inspectedUnit", title: "被检查单位", type: "text", width: 20 },
             { name: "supMaterial", title: "支撑材料", type: "text", width:10 },
             {
                 type: 'control',
                 deleteButton: true,
                 editButton: false,
                 width: 5,
             }
         ],
     };
    $(' .jsgrid').jsGrid(config);
}

function emptyTheForm() {
    // $('.inputbox').val('');  //clear inputbox
    // $('#dialog').fadeOut();  //say goodbye to dialog
    $('#dialog').fadeOut();
	$('#dialogBg').fadeOut();
}

$(function () {
    initDialog('.btn-add', '.addDialog', function () {

        $('.addDialog .respUser').val(userName);

        $('.proCategory, .firstLevel, .secondLevel').focus(function () {
            $(this).parent('div').find('.indicator').animate({height: 'show'}, 100);
            $(this).parent('div').find('.indicator').outerWidth($(this).outerWidth());
        });
        $('.proCategory, .firstLevel, .secondLevel').blur(function () {
            $(this).parent('div').find('.indicator').animate({height: 'hide'}, 100);
            $(this).parent('div').find('.indicator').outerWidth($(this).outerWidth());
        });
    });
    $('.btn-more').click(function () {
        $(' .moreBtnDiv').animate({height: 'toggle'}, 200);
    });
    $('.closeDialogBtn').click(function() {

    });

    $('.searchBtn').click(function (event) {
        event.preventDefault();
        var url = (window.location.href).toString();
        var index = url.indexOf('?');
        var missionId = url.substr(index + 1).split('=')[1];
        console.log(missionId);
        var selectedIndex = $('.searchSelect').get(0).selectedIndex;
        var unknownData = $('.searchbox').val();
        if (unknownData == '' || unknownData == null) {
            alert("请填写要查询的内容");
        }
        var searchData = {
           missionId: missionId
        }
        switch (selectedIndex) {
            case 0:
                searchData.procategory = unknownData;
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                searchData.resPerson = unknownData;
                break;
            default:
                break;
        }
        config.controller = {
            loadData: function() {
                var d = $.Deferred();
    
                $.ajax({
                    type: "post",
                    url: "http://localhost:8080/mm-ssm/inspectionscene/selectByCondition",
                    dataType: "json",
                    data: searchData,
                }).done(function(response) {
                    console.log(response);
                    console.log("search function done!");
                    pagingdata = { data: response, itemsCount: response.length };
                    d.resolve(pagingdata);
                }).fail(function () {
                    console.log("Table can't get search data.");
                });
                return d.promise();
            },
            deleteItem: function (rowData) {

            }
        }
        $('.jsgrid').jsGrid(config);
        // coded by zo7chen
        //
    
    });

    $('.addXcxcBtn').click(function (event) {
        event.preventDefault();
        var proDescription = $('.addDialog .proDescribe').val();
        var applicableLaws = $('.addDialog .propertyRule').val();
        var inspectedUnit = $('.addDialog .company').val();
        var cenManagement = $('.addDialog .department').val();
        var resPerson = $('.addDialog .respUser').val();
        var file = $('.addDialog .uploader input[type=file]')[0].files[0];
        finishDialog('.addDialog');

        var xcxcForm = $('.xcxcForm');
        var formData = new FormData(xcxcForm);//通过form元素构造formData对象
        //下面再逐条添加form数据
        formData.append('proIndex', proIndex);
        formData.append('proDescription', proDescription);
        formData.append('applicableLaws', applicableLaws);
        formData.append('inspectedUnit', inspectedUnit);
        formData.append('cenManagement', cenManagement);
        formData.append('resPerson', resPerson);
        formData.append('file', file);
        formData.append('missionId', missionId);
        debugger;
        $.ajax({
            url: mmssm_url + "inspectionscene/insert",
            type: "POST",
            processData: false,
            contentType: false,//上传formdata的时候需要设置这两个属性
            data: formData,
            success: function (data) {
                resultDialog(true, '.addDialog', function () {

                });
            },
            error: function (error) {
                resultDialog(false, '.addDialog', function () {

                });
            }
        });
    });

    $('.addDialog .uploader input[type=file]').change(function() {
        $(this).parents(".uploader").find(".filename").val($(this).val());
    });


});

var w,h;
function getScreenWH() {
    w = $(window).width();
    h = $(window).height();
    // $('').width(w).height(h);

}

window.onresize = function(){
    getScreenWH();
};
$(window).resize();

